package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.domain.role.RoleDO;
import com.qk.dto.role.RoleDTO;
import com.qk.entity.Role;
import com.qk.management.mapper.RoleMapper;
import com.qk.management.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author: Enid
 * @date: 2025/10/9 11:31
 * @description:
 */
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public Role selectById(Integer id) {
        return roleMapper.selectById(id);
    }
    @Override
    public void updateById(RoleDO roleDO) {
        boolean hasNullField = BeanUtil.hasNullField(roleDO, "remark", "page", "pageSize","createTime","updateTime");
        if (hasNullField) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        Role role = BeanUtil.copyProperties(roleDO, Role.class);
        role.setUpdateTime(LocalDateTime.now());
        roleMapper.update(role);
    }
    @Override
    public void add(Role role) {
        //参数校验
        boolean hasNull = BeanUtil.hasNullField(role, "id","remark","updateTime","createTime");
        if (hasNull){
            throw new RuntimeException("参数错误");
        }
        //补全数据
        role.setCreateTime(LocalDateTime.now());
        role.setUpdateTime(LocalDateTime.now());
        roleMapper.add(role);
    }

    @Override
    public void deleteById(Integer id) {
        roleMapper.deleteById(id);
    }

    /**
     * 获取角色列表
     */
    @Override
    public PageResult<Role> getList(RoleDTO roleDTO) {
        PageHelper.startPage(roleDTO.getPage(),roleDTO.getPageSize());

        List<Role> result =roleMapper.getList(roleDTO);
        Page<Role> page = (Page<Role>) result;

        return PageResult.<Role>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }
    @Override
    public List<Role> list() {
        return roleMapper.list();
    }


}
